<template>
	<view class="page">
		<!-- 页面头部 -->
		<view class="header">
			<view class="nav-bar">
				<view class="nav-left" @click="goBack">
					<image src="/static/svg/dropdown.svg" class="back-icon" />
				</view>
				<text class="nav-title">交易记录</text>
				<view class="nav-right">
					<image src="/static/svg/search.svg" class="search-icon" @click="showSearch" />
				</view>
			</view>
		</view>

		<!-- 筛选条件 -->
		<view class="filter-section">
			<view class="filter-tabs">
				<view 
					class="filter-tab"
					v-for="filter in filterOptions"
					:key="filter.value"
					:class="{ active: selectedFilter === filter.value }"
					@click="selectFilter(filter.value)"
				>
					{{ filter.label }}
				</view>
			</view>
		</view>

		<!-- 交易统计 -->
		<view class="stats-section">
			<view class="stats-item">
				<text class="stats-value income">+¥{{ totalIncome }}</text>
				<text class="stats-label">本月收入</text>
			</view>
			<view class="stats-divider"></view>
			<view class="stats-item">
				<text class="stats-value expense">-¥{{ totalExpense }}</text>
				<text class="stats-label">本月支出</text>
			</view>
		</view>

		<!-- 交易列表 -->
		<view class="transaction-list">
			<view class="date-group" v-for="group in groupedTransactions" :key="group.date">
				<view class="date-header">
					<text class="date-text">{{ group.date }}</text>
					<text class="day-total">{{ group.totalText }}</text>
				</view>
				
				<view class="transactions">
					<view 
						class="transaction-item"
						v-for="transaction in group.transactions"
						:key="transaction.id"
						@click="viewTransactionDetail(transaction)"
					>
						<view class="transaction-left">
							<view class="transaction-icon" :class="transaction.type">
								<image :src="getTransactionIcon(transaction.category)" class="icon" />
							</view>
							<view class="transaction-info">
								<text class="transaction-title">{{ transaction.title }}</text>
								<text class="transaction-desc">{{ transaction.description }}</text>
								<text class="transaction-time">{{ transaction.time }}</text>
							</view>
						</view>
						<view class="transaction-right">
							<text class="transaction-amount" :class="transaction.type">
								{{ transaction.type === 'income' ? '+' : '-' }}¥{{ transaction.amount }}
							</text>
							<text class="transaction-status" :class="transaction.status">
								{{ getStatusText(transaction.status) }}
							</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore" @click="loadMore">
			<text class="load-text">加载更多</text>
		</view>

		<!-- 搜索模态框 -->
		<view class="modal-overlay" v-if="searchVisible" @click="hideSearch">
			<view class="search-modal" @click.stop>
				<view class="search-header">
					<input 
						class="search-input" 
						placeholder="搜索交易记录..."
						v-model="searchKeyword"
						@input="onSearchInput"
					/>
					<view class="search-cancel" @click="hideSearch">取消</view>
				</view>
				<view class="search-results" v-if="searchResults.length > 0">
					<view 
						class="search-item"
						v-for="item in searchResults"
						:key="item.id"
						@click="selectSearchItem(item)"
					>
						<text class="search-title">{{ item.title }}</text>
						<text class="search-amount" :class="item.type">
							{{ item.type === 'income' ? '+' : '-' }}¥{{ item.amount }}
						</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 筛选选项
const filterOptions = ref([
	{ label: '全部', value: 'all' },
	{ label: '收入', value: 'income' },
	{ label: '支出', value: 'expense' },
	{ label: '充值', value: 'recharge' },
	{ label: '提现', value: 'withdraw' }
]);

const selectedFilter = ref('all');

// 交易数据
const transactions = ref([
	{
		id: 1,
		title: '活动报名费',
		description: '篮球比赛报名',
		amount: '50.00',
		type: 'expense',
		category: 'activity',
		status: 'success',
		date: '2024-01-15',
		time: '14:30'
	},
	{
		id: 2,
		title: '账户充值',
		description: '微信支付充值',
		amount: '100.00',
		type: 'income',
		category: 'recharge',
		status: 'success',
		date: '2024-01-15',
		time: '10:20'
	},
	{
		id: 3,
		title: '积分兑换',
		description: '1000积分兑换现金',
		amount: '10.00',
		type: 'income',
		category: 'exchange',
		status: 'success',
		date: '2024-01-14',
		time: '16:20'
	},
	{
		id: 4,
		title: '活动退款',
		description: '羽毛球活动取消退款',
		amount: '30.00',
		type: 'income',
		category: 'refund',
		status: 'success',
		date: '2024-01-14',
		time: '09:15'
	},
	{
		id: 5,
		title: '提现申请',
		description: '银行卡提现',
		amount: '200.00',
		type: 'expense',
		category: 'withdraw',
		status: 'pending',
		date: '2024-01-13',
		time: '11:30'
	},
	{
		id: 6,
		title: '购买装备',
		description: '运动装备购买',
		amount: '80.00',
		type: 'expense',
		category: 'shopping',
		status: 'success',
		date: '2024-01-12',
		time: '20:45'
	}
]);

// 搜索相关
const searchVisible = ref(false);
const searchKeyword = ref('');
const searchResults = ref([]);

// 加载更多
const hasMore = ref(false);

// 过滤后的交易
const filteredTransactions = computed(() => {
	if (selectedFilter.value === 'all') {
		return transactions.value;
	}
	return transactions.value.filter(t => {
		if (selectedFilter.value === 'recharge') {
			return t.category === 'recharge';
		}
		if (selectedFilter.value === 'withdraw') {
			return t.category === 'withdraw';
		}
		return t.type === selectedFilter.value;
	});
});

// 按日期分组的交易
const groupedTransactions = computed(() => {
	const groups = {};
	
	filteredTransactions.value.forEach(transaction => {
		const date = transaction.date;
		if (!groups[date]) {
			groups[date] = {
				date: formatDate(date),
				transactions: [],
				totalIncome: 0,
				totalExpense: 0
			};
		}
		groups[date].transactions.push(transaction);
		
		if (transaction.type === 'income') {
			groups[date].totalIncome += parseFloat(transaction.amount);
		} else {
			groups[date].totalExpense += parseFloat(transaction.amount);
		}
	});
	
	// 转换为数组并排序
	return Object.values(groups).map(group => ({
		...group,
		totalText: group.totalIncome > 0 || group.totalExpense > 0 
			? `收入¥${group.totalIncome.toFixed(2)} 支出¥${group.totalExpense.toFixed(2)}`
			: ''
	})).sort((a, b) => new Date(b.date) - new Date(a.date));
});

// 统计数据
const totalIncome = computed(() => {
	return transactions.value
		.filter(t => t.type === 'income' && isCurrentMonth(t.date))
		.reduce((sum, t) => sum + parseFloat(t.amount), 0)
		.toFixed(2);
});

const totalExpense = computed(() => {
	return transactions.value
		.filter(t => t.type === 'expense' && isCurrentMonth(t.date))
		.reduce((sum, t) => sum + parseFloat(t.amount), 0)
		.toFixed(2);
});

// 选择筛选条件
const selectFilter = (value) => {
	selectedFilter.value = value;
};

// 显示搜索
const showSearch = () => {
	searchVisible.value = true;
};

// 隐藏搜索
const hideSearch = () => {
	searchVisible.value = false;
	searchKeyword.value = '';
	searchResults.value = [];
};

// 搜索输入
const onSearchInput = () => {
	if (!searchKeyword.value.trim()) {
		searchResults.value = [];
		return;
	}
	
	searchResults.value = transactions.value.filter(t => 
		t.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
		t.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
	);
};

// 选择搜索结果
const selectSearchItem = (item) => {
	hideSearch();
	viewTransactionDetail(item);
};

// 查看交易详情
const viewTransactionDetail = (transaction) => {
	uni.showModal({
		title: '交易详情',
		content: `交易类型：${transaction.title}\n交易金额：¥${transaction.amount}\n交易时间：${transaction.date} ${transaction.time}\n交易状态：${getStatusText(transaction.status)}\n描述：${transaction.description}`,
		showCancel: false
	});
};

// 获取交易图标
const getTransactionIcon = (category) => {
	const iconMap = {
		activity: '/static/svg/walking.svg',
		recharge: '/static/svg/add.svg',
		exchange: '/static/svg/gift.svg',
		refund: '/static/svg/trend-up.svg',
		withdraw: '/static/svg/minus.svg',
		shopping: '/static/svg/gift.svg'
	};
	return iconMap[category] || '/static/svg/more.svg';
};

// 获取状态文本
const getStatusText = (status) => {
	const statusMap = {
		success: '成功',
		pending: '处理中',
		failed: '失败'
	};
	return statusMap[status] || '未知';
};

// 格式化日期
const formatDate = (dateString) => {
	const date = new Date(dateString);
	const today = new Date();
	const yesterday = new Date(today);
	yesterday.setDate(yesterday.getDate() - 1);
	
	if (dateString === today.toISOString().split('T')[0]) {
		return '今天';
	} else if (dateString === yesterday.toISOString().split('T')[0]) {
		return '昨天';
	} else {
		return `${date.getMonth() + 1}月${date.getDate()}日`;
	}
};

// 判断是否为当月
const isCurrentMonth = (dateString) => {
	const date = new Date(dateString);
	const now = new Date();
	return date.getMonth() === now.getMonth() && date.getFullYear() === now.getFullYear();
};

// 加载更多
const loadMore = () => {
	uni.showToast({
		title: '暂无更多数据',
		icon: 'none'
	});
};

// 返回上一页
const goBack = () => {
	uni.navigateBack();
};

onMounted(() => {
	// 页面加载时的初始化操作
});
</script>

<style scoped>
.page {
	min-height: 100vh;
	background: #f8f9fa;
}

/* 页面头部 */
.header {
	background: white;
	padding-top: var(--status-bar-height);
}

.nav-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 20px;
}

.nav-left {
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
	width: 20px;
	height: 20px;
	transform: rotate(-90deg);
}

.nav-title {
	font-size: 18px;
	font-weight: bold;
	color: #333;
}

.nav-right {
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.search-icon {
	width: 20px;
	height: 20px;
}

/* 筛选条件 */
.filter-section {
	background: white;
	padding: 0 20px;
	border-bottom: 1px solid #f0f0f0;
}

.filter-tabs {
	display: flex;
	gap: 20px;
}

.filter-tab {
	padding: 15px 0;
	font-size: 14px;
	color: #666;
	position: relative;
	cursor: pointer;
}

.filter-tab.active {
	color: #667eea;
	font-weight: bold;
}

.filter-tab.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	height: 2px;
	background: #667eea;
}

/* 交易统计 */
.stats-section {
	background: white;
	display: flex;
	padding: 20px;
	margin-bottom: 10px;
}

.stats-item {
	flex: 1;
	text-align: center;
}

.stats-value {
	font-size: 20px;
	font-weight: bold;
	display: block;
	margin-bottom: 5px;
}

.stats-value.income {
	color: #28a745;
}

.stats-value.expense {
	color: #dc3545;
}

.stats-label {
	font-size: 12px;
	color: #999;
}

.stats-divider {
	width: 1px;
	background: #f0f0f0;
	margin: 0 20px;
}

/* 交易列表 */
.transaction-list {
	padding: 0 20px;
}

.date-group {
	margin-bottom: 20px;
}

.date-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10px 0;
}

.date-text {
	font-size: 14px;
	font-weight: bold;
	color: #333;
}

.day-total {
	font-size: 12px;
	color: #999;
}

.transactions {
	background: white;
	border-radius: 12px;
	overflow: hidden;
}

.transaction-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px;
	border-bottom: 1px solid #f8f9fa;
	cursor: pointer;
}

.transaction-item:last-child {
	border-bottom: none;
}

.transaction-item:active {
	background: #f8f9fa;
}

.transaction-left {
	display: flex;
	align-items: center;
	flex: 1;
}

.transaction-icon {
	width: 40px;
	height: 40px;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 15px;
}

.transaction-icon.income {
	background: #d4edda;
}

.transaction-icon.expense {
	background: #f8d7da;
}

.icon {
	width: 20px;
	height: 20px;
}

.transaction-info {
	flex: 1;
}

.transaction-title {
	font-size: 16px;
	color: #333;
	display: block;
	margin-bottom: 4px;
}

.transaction-desc {
	font-size: 12px;
	color: #999;
	display: block;
	margin-bottom: 2px;
}

.transaction-time {
	font-size: 11px;
	color: #ccc;
	display: block;
}

.transaction-right {
	text-align: right;
}

.transaction-amount {
	font-size: 16px;
	font-weight: bold;
	display: block;
	margin-bottom: 4px;
}

.transaction-amount.income {
	color: #28a745;
}

.transaction-amount.expense {
	color: #dc3545;
}

.transaction-status {
	font-size: 11px;
	display: block;
}

.transaction-status.success {
	color: #28a745;
}

.transaction-status.pending {
	color: #ffc107;
}

.transaction-status.failed {
	color: #dc3545;
}

/* 加载更多 */
.load-more {
	text-align: center;
	padding: 20px;
}

.load-text {
	font-size: 14px;
	color: #667eea;
}

/* 搜索模态框 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
}

.search-modal {
	background: white;
	padding-top: var(--status-bar-height);
	height: 100%;
}

.search-header {
	display: flex;
	align-items: center;
	padding: 15px 20px;
	border-bottom: 1px solid #f0f0f0;
	gap: 15px;
}

.search-input {
	flex: 1;
	padding: 10px 15px;
	background: #f8f9fa;
	border-radius: 20px;
	font-size: 14px;
}

.search-cancel {
	font-size: 14px;
	color: #667eea;
}

.search-results {
	padding: 20px;
}

.search-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f8f9fa;
	cursor: pointer;
}

.search-item:active {
	background: #f8f9fa;
}

.search-title {
	font-size: 16px;
	color: #333;
}

.search-amount {
	font-size: 16px;
	font-weight: bold;
}

.search-amount.income {
	color: #28a745;
}

.search-amount.expense {
	color: #dc3545;
}
</style> 